<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">楼宇名称：</div>
      <el-input v-model="params.name" placeholder="请输入内容" class="search-main" />
      <el-button type="primary" @click="search">查询</el-button>
      <el-button type="error" @click="refresh">刷新页面</el-button>
    </div>
    <el-button type="primary" @click="edit(null)">添加楼宇</el-button>
    <el-button type="success" plain @click="exportToExcel">导出excel</el-button>
    <!-- 表格区域 -->
    <div class="table">
      <el-table
        style="width: 100%"
        :data="list"
      >
        <el-table-column
          type="index"
          :index="indexMethod"
          label="序号"
        />
        <el-table-column
          label="楼宇名称"
          width="180"
          prop="name"
        />
        <el-table-column
          label="层数"
          prop="floors"
        />
        <el-table-column
          label="在管面积(m²)"
          width="120"
          prop="area"
        />
        <el-table-column
          label="物业费(元/m²)"
          width="120"
          prop="propertyFeePrice"
        />
        <el-table-column
          label="状态"
          prop="status"
        >
          <template #default="scope">
            {{ formatStatus(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="edit(scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="text"
              @click="del(scope.row.id)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </div>
    <!-- 分页 -->
    <el-pagination
      :current-page="params.page"
      :page-sizes="[5, 8, 10, 15]"
      :page-size="params.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
    <!-- 弹窗 -->
    <el-dialog
      :title="form.id?'编辑楼宇':'添加楼宇' "
      :visible.sync="dialogVisible"
      width="30%"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" class="demo-ruleForm">
        <el-form-item label="楼宇名称" prop="name" label-width="80px">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="楼宇层数" prop="floors" label-width="80px">
          <el-input v-model.number="form.floors" />
        </el-form-item>
        <el-form-item label="在管面积" prop="area" label-width="80px">
          <el-input v-model.number="form.area" />
        </el-form-item>
        <el-form-item label="物业费" prop="propertyFeePrice" label-width="80px">
          <el-input v-model.number="form.propertyFeePrice" />
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addPark">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getParkListAPI, addParkAPI, delParkAPI, getParkDetailAPI, editParkAPI } from '@/api/building'
import { utils, writeFileXLSX } from 'xlsx'
export default {
  name: 'Building',
  data() {
    return {
      form: {
        name: '',
        floors: '', // 楼宇层数
        area: '', // 楼宇面积
        propertyFeePrice: '' // 物业费
      },
      rules: {
        name: [
          { required: true, message: '请输入楼宇名称', trigger: 'blur' }
        ],
        floors: [
          { required: true, message: '请输入楼宇层数', trigger: 'blur' },
          { pattern: /^([0-9]|1[0-9]|20)$/, message: '不能超过20层', trigger: ['blur', 'change'] }
        ],
        area: [
          { required: true, message: '请输入楼宇面积', trigger: 'blur' }
        ],
        propertyFeePrice: [
          { required: true, message: '请输入物业费', trigger: 'blur' }
        ]

      },
      // 是否显示添加楼宇弹窗
      dialogVisible: false,
      list: [],
      // 页码
      params: {
        page: 1,
        pageSize: 5,
        name: ''
      },
      // 总条数
      total: 0
    }
  },
  created() {
    this.getParkList()
  },
  methods: {

    // 点击删除
    del(id) {
      // console.log(id)
      this.$confirm('此操作将永久删除该楼宇, 是否继续?', '提示', {
        type: 'warning'
      }
      ).then(async() => {
        await delParkAPI(id)
        this.$message.success('删除成功')
        this.getParkList()
      }
      ).catch(
        () => {}
      )
    },
    // 点击弹窗确定
    addPark() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        console.log(this.form)
        if (this.form.id) {
          delete this.form.status
          await editParkAPI(this.form)
          this.$message.success('修改成功')
          // this.$refs.form.resetFields()
        } else {
          // 调取添加接口
          await addParkAPI(this.form)
          // 提示框
          this.$message.success('添加成功')
        }
        // 清空表单
        this.$refs.form.resetFields()
        // 关闭弹窗
        this.dialogVisible = false
        // 刷新列表
        this.getParkList()
      })
    },

    // 点击刷新
    refresh() {
      delete this.params.name
      this.getParkList()
    },
    // 点击查询
    search() {
      this.page = 1
      this.getParkList()
    },
    // 条数改变时 pagesize
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      this.params.pageSize = val
      this.getParkList()
    },
    // 页码改变时 page
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`)
      this.params.page = val
      this.getParkList()
    },
    // 状态格式化
    formatStatus(status) {
      const statusMap = {
        0: '租赁中',
        1: '闲置中'
      }
      return statusMap[status]
    },
    // 序号
    indexMethod(index) {
      return (this.params.page - 1) * this.params.pageSize + index + 1
    },
    // 获取列表
    async getParkList() {
      const res = await getParkListAPI(this.params)
      // console.log(res)
      this.list = res.data.rows
      this.total = res.data.total
    },
    // 点击编辑
    async edit(row) {
      this.dialogVisible = true
      // console.log(row)
      if (row !== null) {
        this.form = row
        await getParkDetailAPI(row.id)
      } else {
        this.form = {
          name: '',
          floors: '', // 楼宇层数
          area: '', // 楼宇面积
          propertyFeePrice: '' // 物业费
        }
      }
    },
    // 导出excel表格
    async exportToExcel() {
      // 引入 xlsx 库
      const XLSX = require('xlsx')
      // 创建工作簿
      const workbook = XLSX.utils.book_new()
      const res = await getParkListAPI(this.params)
      const tableHeader = ['name', 'floors', 'area', 'propertyFeePrice', 'status']
      // 处理数据保证
      const sheetData = res.data.rows.map((item) => {
        const obj = {}
        tableHeader.forEach(key => {
          obj[key] = item[key]
        })
        return obj
      })

      // 创建一个工作表
      const worksheet = utils.json_to_sheet(sheetData)
      // 创建一个新的工作簿
      // 把工作表添加到工作簿
      utils.book_append_sheet(workbook, worksheet, 'Data')
      // 改写表头
      utils.sheet_add_aoa(worksheet, [['楼宇名称', '层数', '在管面积(㎡)', '物业费(㎡)', '状态']], { origin: 'A1' })
      writeFileXLSX(workbook, 'SheetJSVueAoO.xlsx')
    }
  }
}
</script>

<style lang="scss" scoped>
 .page-container{
    padding:4px 0px;
    text-align: right;
  }
.department-container{
  padding:10px;
}
.search-container{
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237,237,237,.9);;
  padding-bottom: 20px;
  .search-label{
    width:100px;
  }
  .search-main{
    width: 220px;
    margin-right: 10px;
  }
}
</style>
